﻿using System;
using System.Linq;
using System.Xml.Linq;

namespace Lastfm7.Services
{
    public class UserData
    {
        public string Username { get; private set; }
        public string Country { get; private set; }
        public string Gender { get; private set; }
        public int Playcount { get; private set; }
        public int Age { get; private set; }
        public Uri AvatarUrl { get; private set; }
        
        public UserData(XDocument response)
        {
            if (response.Root == null)
                throw new ArgumentException("No root tag.");

            var user = response.Root.Element("user");
            if (user == null)
                throw new ArgumentException("No user tag.");

            var avatarUrl = (from img in user.Elements("image")
                             let size = img.Attribute("size")
                             where size != null && size.Value == "extralarge"
                             select img.Value).SingleOrDefault();

            if (avatarUrl == null)
                throw new ArgumentException("No extralarge image.");

            try
            {
                Username = user.Element("name").Value.ToLower();
                Country = user.Element("country").Value.ToLower();
                Gender = user.Element("gender").Value.ToLower();
                Playcount = int.Parse(user.Element("playcount").Value);
                Age = int.Parse(user.Element("age").Value);
                AvatarUrl = new Uri(avatarUrl);
            }
            catch (NullReferenceException)
            {
                throw new ArgumentException("Can't read user details from XML.");
            }
        }
    }
}
